// pages/cancel_order/cancel_order.js
var common = require("../../common/common.js").common;

var un = require("../../siteinfo.js");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        array: [ "选择申请原因", "商品有质量问题", "没有收到货", "商品少发漏发发错", "商品与描述不一致", "质疑假货", "收到商品时有损坏", "其他" ],
        //退货原因
        index1: 0,
        //退货原因索引
        order_pro: [],
        //订单商品
        trade_no: "",
        //订单号
        status: 2,
        //订单状态
        array2: [ "选择售后类型", "退货退款", "我要换货" ],
        //申请售后原因
        index2: 0,
        //申请售后原因索引
        imgbox: [],
        //上传的图片
        refund_price: 0,
        //退款金额
        cause_des: "",
        //问题描述
        apply_from: 1,
        //申请来源
        delivery_paid: 0,
        //团长配送费或者运费
        explain: "申请取消时，请先联系客服",
        applyBtn: false
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        let that = this;
        let info = JSON.parse(decodeURIComponent(options.info));
        let ids = [];
        let order_info = info.order_info;
        order_info.map(x => {
            ids.push(x.id);
        });
        that.setData({
            id: info.order.id,
            ids: ids.join(","),
            domain: app.globalData.domain.slice(0, -10)
        });
        this.getData();
        this.getBase();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    //选择退货原因
    choose_reason: function(e) {
        if (this.data.descriptionArr[e.detail.value]) {
            wx.showModal({
                title: "提示",
                content: this.data.descriptionArr[e.detail.value],
                showCancel: false
            });
        }
        this.setData({
            index1: e.detail.value
        });
    },
    //获取数据
    getData: function() {
        let that = this;
        let id = that.data.id;
        common.request({
            endpoint: "Order/order_close/orderafter_all",
            method: "post",
            data: {
                id: id
            },
            success: function(res) {
                var reasonArr = [];
                var descriptionArr = [];
                res.extra.after_reason.map(x => {
                    if (x.status == 1 && (x.type == 1 || x.type == 5)) {
                        reasonArr.push(x.reason);
                        descriptionArr.push(x.description);
                    }
                });
                that.setData({
                    details: res.extra.info,
                    after_img: res.extra.after_img,
                    array: reasonArr,
                    descriptionArr: descriptionArr
                });
            }
        });
    },
    //选择商品
    select: function(e) {
        let that = this;
        let order_pro = that.data.order_pro;
        let index = e.currentTarget.dataset.index;
        if (order_pro[index].select == 0) {
            order_pro[index].select = 1;
        } else {
            order_pro[index].select = 0;
        }
        that.setData({
            order_pro: order_pro
        });
    },
    //上传图片
    uploadImage: function() {
        var that = this;
        let imgbox = that.data.imgbox;
        let uniacid;
        if (wx.getStorageSync("uniacid")) {
            uniacid = wx.getStorageSync("uniacid");
        } else {
            uniacid = un.uniacid;
        }
        let domian = app.globalData.domain;
        wx.chooseImage({
            count: 3,
            //最多可以选择的图片总数
            sizeType: [ "compressed" ],
            // 可以指定是原图还是压缩图，默认二者都有
            sourceType: [ "album", "camera" ],
            // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                var tempFilePaths = res.tempFilePaths;
                //启动上传等待中...
                                wx.showLoading({
                    title: "正在上传..."
                });
                var i = 0;
                var length = tempFilePaths.length;
                var upload = function() {
                    wx.uploadFile({
                        url: domian + "Order/order_close/imgfile",
                        filePath: tempFilePaths[i],
                        name: "file",
                        formData: {},
                        header: {
                            "Content-Type": "multipart/form-data",
                            uniacid: uniacid
                        },
                        success: function(res) {
                            var data = JSON.parse(res.data);
                            imgbox.push(data.Url);
                            i++;
                            if (i < length) {
                                upload();
                            } else {
                                wx.hideLoading();
                                that.setData({
                                    imgbox: imgbox
                                });
                            }
                        },
                        fail: function(res) {
                            wx.hideToast();
                            wx.showModal({
                                title: "错误提示",
                                content: "上传图片失败",
                                showCancel: false,
                                success: function(res) {}
                            });
                        }
                    });
                };
                upload();
            }
        });
    },
    //删除图片
    delete_img: function(e) {
        let that = this;
        let index = that.data.index;
        let imgbox = that.data.imgbox;
        imgbox.splice(index, 1);
        that.setData({
            imgbox: imgbox
        });
    },
    //计算退款金额
    clculate: function(order_pro, delivery_paid) {
        let that = this;
        let refund_price = 0;
        let status = that.data.status;
        var actually_paid = that.data.actually_paid;
        var chooseNum = 0;
        var order_status = that.data.order_status;
        var proNum = 0;
        that.setData({
            refund_price: refund_price.toFixed(2)
        });
    },
    //保存问题描述
    save_cause: function(e) {
        this.setData({
            cause_des: e.detail.value
        });
    },
    //取消订单
    apply: function(e) {
        let that = this;
        let apply_from = that.data.apply_from;
        let ids = that.data.ids;
        let index1 = that.data.index1;
        let array1 = that.data.array;
        let imgbox = that.data.imgbox;
        let cause_des = that.data.cause_des;
        let status = that.data.status;
        let aftermarket_type = 0;
        that.setData({
            applyBtn: false
        });
        //禁用按钮
                that.setData({
            applyBtn: true
        });
        if (index1 == 0) {
            wx.showModal({
                title: "提醒",
                content: "请选择申请原因",
                showCancel: false
            });
            //解禁按钮
                        that.setData({
                applyBtn: false
            });
            return false;
        }
        if (that.data.refund_img == 1 && !imgbox.length) {
            wx.showModal({
                title: "提示",
                content: "请上传凭证图片!",
                showCancel: false
            });
            //解禁按钮
                        that.setData({
                applyBtn: false
            });
            return false;
        }
        let aftermarket_reason = array1[parseInt(index1)];
        common.request({
            endpoint: "Order/order_close/all_aftermarket",
            method: "post",
            data: {
                aftermarket_type: aftermarket_type,
                item: ids,
                aftermarket_reason: aftermarket_reason,
                aftermarket_description: cause_des,
                file: imgbox,
                apply_from: 1,
                aftermarket_reason_id: that.data.index1
            },
            header: {
                "content-type": "application/json"
            },
            success: function(res) {
                wx.showToast({
                    title: "取消成功"
                });
                setTimeout(() => {
                    wx.switchTab({
                        url: "/pages/order/order",
                        success: function(e) {
                            var page = getCurrentPages().pop();
                            if (page == undefined || page == null) return;
                            page.onLoad();
                        }
                    });
                }, 500);
            },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: err.message,
                    showCancel: false,
                    cancelText: "取消",
                    cancelColor: "",
                    confirmText: "确定",
                    confirmColor: "",
                    success: function(res) {
                        //解禁按钮
                        that.setData({
                            applyBtn: false
                        });
                    },
                    complete: function(res) {}
                });
            }
        });
    },
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    refund_img: res.extra.refund_img,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长"
                });
            }
        });
    },
    refundMoney(item) {
        var refund_price = item.after_discount_price * item.pro.refundNum == 0 ? "0.00" : (Math.floor(item.after_discount_price * item.pro.refundNum * 100) / 100).toFixed(2);
        this.setData({
            refund_price: refund_price
        });
    }
});